local M = {}

M.lint_with_ruff = function()
    -- Get the current buffer's full file path
    local filepath = vim.fn.expand('%:p')

    -- Command to run Ruff on the current file
    local command = 'ruff check ' .. filepath

    -- Execute the command and capture output
    local handle = io.popen(command)
    local result = handle:read("*a")
    handle:close()

    -- Clear the quickfix list before populating it
    vim.fn.setqflist({}, ' ')

    -- Only process output if it exists
    if result ~= "" then
        local qflist = {}

        -- Split output into lines
        for _, line in ipairs(vim.split(result, "\n")) do
            if line ~= "" then
                -- Split each line into components (filename:line:column: message)
                local parts = vim.split(line, ":")

                if #parts >= 4 then  -- Ensure there's at least one message part
                    table.insert(qflist, {
                        filename = parts[1],  -- File path
                        lnum = tonumber(parts[2]),  -- Line number
                        col = tonumber(parts[3]),  -- Column number
                        text = table.concat(parts, ":", 4),  -- Join remaining parts as message
                    })
                    break
                end
            end
        end

        -- Set the quickfix list with the gathered items
        if #qflist > 0 then
            vim.fn.setqflist(qflist)

            -- Open the quickfix window to display results
            vim.cmd('copen 4')
        else
            vim.cmd('cclose')
        end
    end
end

M.lint_with_ruff_2 = function()
    -- Get the current buffer's full file path
    local filepath = vim.fn.expand('%:p')
    -- Command to run Ruff on the current file
    local command = 'ruff check --output-format=json ' .. filepath
    -- Execute the command and capture output
    local handle = io.popen(command)
    local result = handle:read("*a")
    handle:close()

    -- Clear existing diagnostics
    vim.diagnostic.reset()
    local ns_id = vim.api.nvim_create_namespace("ruff")

    -- Only process output if it exists
    if result ~= "" then
        local diagnostics = {}
        local json_result = vim.json.decode(result)

        for _, item in ipairs(json_result) do
            table.insert(diagnostics, {
                bufnr = vim.fn.bufnr(item.filename),
                lnum = item.location.row - 1,  -- Convert to 0-based index
                col = item.location.column - 1,  -- Convert to 0-based index
                message = item.message,
                severity = vim.diagnostic.severity.ERROR,
                source = "ruff",
            })
            break
        end

        -- Set diagnostics for the current buffer
        vim.diagnostic.set(ns_id, 0, diagnostics)
    end
end

return M
-- EOP
